from __future__ import annotations

import re

from datetime import datetime
from typing import List

from fastapi import Depends, APIRouter, HTTPException
from pydantic import BaseModel, Field
from sqlalchemy import case
from sqlalchemy.orm import Session
from starlette import status

from common.avatra import RandomAvatarsService
from common.RsaUtil import RsaUtil
from common.sqlalchemy_db import SqlalchemyX
from modules.User import User

from modules.mod import Friendship, Message
from modules.http_resp import HttpResponse, ResponseSuccess
from service.DialogService import DialogService


class AddFriendShip(BaseModel):
    fromUserId: int
    toUserId: int

class DelFriendShip(BaseModel):
    user_id: int
    del_user_id: int

class FriendshipResponse(BaseModel):
    from_user_id: str
    to_user_id: str
    add_friend_time: datetime
    friendship_state: int
    friendship_type: int
    top_if: int
    agree_time: datetime

router = APIRouter()
dialog_service = DialogService()
dialog_service = Message()

@router.post("/add")
async def addFriend(request: AddFriendShip, db: Session = Depends(SqlalchemyX.get_db)):
    friendship = Friendship()
    friendship.from_user_id = request.fromUserId
    friendship.to_user_id = request.toUserId
    friendship.friendship_type =1
    friendship.friendship_state = 1
    friendship.add_friend_time = datetime.now()
    friendship.top_if = 0
    db.add(friendship)
    db.commit()
    await dialog_service.update_dialog_mes(
        {"dialog_from_id": request.toUserId, "dialog_target_id": request.fromUserId},
        {
            "dialog_id": None,
            "dialog_from_id": request.toUserId,
            "dialog_target_id": request.fromUserId,
        }
    )
    return ResponseSuccess({"success": True})



def get_friends_ids(db: Session, user_id: int) -> List[int]:
    friend_ids = db.query(
        case(
            (Friendship.from_user_id == user_id, Friendship.to_user_id),
            else_=Friendship.from_user_id
        ).label("friend_id")
    ).filter(
        (Friendship.from_user_id == user_id) |
        (Friendship.to_user_id == user_id)
    ).all()

    return [row.friend_id for row in friend_ids]

def check_user(db: Session, user_id: int):
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

def get_all_friends_mes(db: Session, friend_ids: List[int]) -> List[dict]:
    users = db.query(User).filter(User.user_id.in_(friend_ids)).all()
    return [
        {
            "id": user.user_id,
            "user_name": user.user_name,
            "user_avatar": user.user_avatar,
            "user_reg_time": user.user_reg_time,
            "user_lastLogin_time": user.user_lastLogin_time,
            "user_state": user.user_state,
            "user_socketId": user.user_socketId,
            "user_preferSetting_id": user.user_preferSetting_id
        }
        for user in users
    ]

def classify_friends_by_char(friends: List[dict]) -> dict:
    from collections import defaultdict
    result = defaultdict(list)

    def get_initial(name: str) -> str:
        name = name.strip().upper()
        if not name:
            return '#'
        first_char = name[0]
        if re.match(r'[A-Z]', first_char):
            return first_char
        else:
            return '#'

    for friend in friends:
        initial = get_initial(friend["user_name"])
        result[initial].append(friend)

    # 转换为有序字典（可选）
    sorted_result = dict(sorted(result.items()))
    return sorted_result


@router.get("/list")
async def allFriends(userId : str, db: Session = Depends(SqlalchemyX.get_db)):
    # Step 1: 检查用户是否存在
    check_user(db, userId)

    # Step 2: 获取所有好友 ID
    friend_ids = get_friends_ids(db, userId)

    # Step 3: 获取所有好友信息
    friend_mess = get_all_friends_mes(db, friend_ids)
    # Step 4: 分类整理
    classified_friends = classify_friends_by_char(friend_mess)

    return ResponseSuccess({
            "userId": userId,
            "friendsCount": len(friend_ids),
            "friendsList": classified_friends
        })


